package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"ver-sys/cache"
	"ver-sys/models"
)

func OrderAdd(c *gin.Context) {
	ordername := c.PostForm("ordername")
	orderaddress := c.PostForm("orderaddress")
	orderprice := c.PostForm("orderprice")
	data := models.Order{
		OrderName:    ordername,
		OrderAddress: orderaddress,
		OrderPrice:   orderprice,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var order []models.Order
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  order,
		"total": total,
	})
	return
}
